import {
  Inject,
  Controller,
  Get,
  Post,
  Files,
  Query,
  Fields,
} from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { PREFIX } from '../contanst';
import { BaseController } from './base.controller';
import { FileService } from '../service/file.service';
import { EXCEL_MAP } from '../contanst/expertCommission';
import { ExpertCommissionService } from '../service/expertCommission.service';
import { toLower } from 'lodash';
import { Like } from 'typeorm';

const DESCRIPTION = '达人佣金';
@Controller(PREFIX)
export class APIController extends BaseController {
  @Inject()
  ctx: Context;

  @Inject()
  expertCommissionService: ExpertCommissionService;

  @Get('/expertCommission', {
    description: `${DESCRIPTION}列表`,
  })
  async index(
    @Query('size') size = 10,
    @Query('page') page = 1,
    @Query('store_name') store_name,
    @Query('order_number') order_number
  ) {
    const list = await this.expertCommissionService.page({
      data: {
        size,
        page,
        store_name: store_name && Like(`%${store_name}%`),
        order_number: order_number && Like(`%${order_number}%`),
      },
    });
    return this.success(list);
  }

  @Inject()
  file: FileService;

  @Post('/expertCommission/import', {
    description: `${DESCRIPTION}导入`,
  })
  async import(
    @Files() files,
    @Fields('data_date') data_date,
    @Fields('store_name') store_name
  ) {
    const file = files[0];
    const data: any = await this.file.importExcel(file);
    const tableData = data?.[0]?.data;
    const tableHeader = tableData?.[0];
    const tableBody = tableData?.splice?.(1);
    const obj = {};
    Object.keys(EXCEL_MAP).forEach(key => {
      const index = tableHeader?.findIndex?.(
        item => toLower(item).trim() === toLower(key).trim()
      );
      obj[EXCEL_MAP[key]] = index;
    });
    const records: any[] = [];
    tableBody.forEach(item => {
      const record: any = {};
      Object.keys(obj).map(key => {
        record[key] = item[obj[key]]?.replace?.(/\t/g, '') || item[obj[key]];
      });
      record.store_name = store_name;
      record.data_date = data_date;
      records.push(record);
    });
    this.expertCommissionService.upsert(records);

    return this.success();
  }
}
